package com.dgshanger.sanhxiaofeisc.ui.home.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.AMapUtils
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.model.LatLng
import com.blankj.utilcode.util.ScreenUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.adapter.ShopDetailsAdapter
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.entity.ShopDetailsEntity
import com.dgshanger.sanhxiaofeisc.mvp.contract.ShopDetailsContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.ShopDetailsPresenter
import com.dgshanger.sanhxiaofeisc.ui.home.utils.ImageLoader
import com.dgshanger.sanhxiaofeisc.ui.home.utils.NavigateDialog
import com.dgshanger.sanhxiaofeisc.ui.home.utils.OpenNavigationUtils
import com.dgshanger.sanhxiaofeisc.ui.home.utils.TextDialog
import com.dhn.library.PullZoomRecyclerView
import com.google.gson.Gson
import com.xx.baseuilibrary.mvp.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_shop_details.*
import kotlinx.android.synthetic.main.view_shop_details_foot.view.*
import kotlinx.android.synthetic.main.view_shop_details_head.view.*
import kotlinx.android.synthetic.main.view_shop_details_head2.view.*
import java.math.BigDecimal

/**
 * Created by JacobHHH on 2018/4/18.
 * 商家详情
 */
class ShopDetailsActivity : BaseMvpActivity<ShopDetailsContract.Model,ShopDetailsContract.View,ShopDetailsPresenter>(),ShopDetailsContract.View, View.OnClickListener {

    private lateinit var mAdapter: ShopDetailsAdapter
    private  var mAMap : AMap? = null
    private lateinit var mShop_id : String
    private lateinit var mComment_score : String
    private var needPermission : Array<String> ?= arrayOf(Manifest.permission.CALL_PHONE)


    override fun createPresenter(): ShopDetailsPresenter = ShopDetailsPresenter()

    override fun getActivityLayoutId(): Int = R.layout.activity_shop_details


    /*重写onCreate方法*/
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mHeaderView2.mapView.onCreate(savedInstanceState)
        mHeaderView2.mapView
        if (mAMap == null) {
            mAMap = mHeaderView2.mapView.getMap()
        }
        //隐藏缩放按钮
        mAMap!!.getUiSettings().setZoomControlsEnabled(false)//实例化UiSettings类对象
        mAMap!!.getUiSettings().setAllGesturesEnabled(false)//实例化UiSettings类对象

    }

    override fun initData() {
        mShop_id = intent.getStringExtra("shop_id")//商家id
        mComment_score = intent.getStringExtra("comment_score")//评分分数
        initView()
        getPresenter().loadData(mShop_id)
    }

    private lateinit var rec_shop_details : PullZoomRecyclerView
    private fun initView() {
        rec_shop_details=findViewById(R.id.rec_shop_details)
        rec_shop_details.layoutManager=LinearLayoutManager(mContext)
        mAdapter = ShopDetailsAdapter(R.layout.item_shop_details, ArrayList())
        mAdapter.addHeaderView(getHeaderView())
        mAdapter.addHeaderView(getHeaderViewBottom())
        mAdapter.addFooterView(getFooterView())
        rec_shop_details.adapter= mAdapter

    }

    private lateinit var mHeadImage : ImageView
    private lateinit var mHeaderView1 :View
    private fun getHeaderView(): View? {
        val localDisplayMetrics =  DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(localDisplayMetrics)
        //获取屏幕的高
        val screenHeight = localDisplayMetrics.heightPixels
        //获取屏幕宽
        val screenWidth = localDisplayMetrics.widthPixels;
        val headerHeight = (15.0F * (screenWidth / 16.0F)).toInt()
        val containerParams =  RecyclerView.LayoutParams(screenWidth, headerHeight)
        val frameLayout = FrameLayout(mContext)
        frameLayout.id=0
        frameLayout.layoutParams=containerParams
        mHeadImage = ImageView(mContext)
        //设置缩放类型
        //mHeadImage!!.setImageResource(R.drawable.ic_launcher_background)
        mHeadImage.scaleType=ImageView.ScaleType.CENTER_CROP
        //为ImageView设置布局参数
        val imageLayoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        mHeadImage.setLayoutParams(imageLayoutParams)
        mHeaderView1 = View.inflate(mContext, R.layout.view_shop_details_head, null)
        mHeaderView1.iv_close.setOnClickListener(this)
        mHeaderView1.rl_photo.setOnClickListener(this)
        frameLayout.addView(mHeadImage)
        frameLayout.addView(mHeaderView1)
        rec_shop_details.setScreenHeight(ScreenUtils.getScreenHeight())
        rec_shop_details.setHeaderContainer(frameLayout)
        return frameLayout
    }

    private lateinit var mHeaderView2 : View
    private fun getHeaderViewBottom(): View? {
        mHeaderView2 = View.inflate(mContext, R.layout.view_shop_details_head2, null)
        mHeaderView2.rl_level.setOnClickListener(this)
        mHeaderView2.tv_check_all.setOnClickListener(this)
        mHeaderView2.rl_3.setOnClickListener(this)
        mHeaderView2.tv_grade.text=mComment_score
        return mHeaderView2
    }

    private lateinit var mFooterView : View
    private fun getFooterView(): View? {
        mFooterView = View.inflate(mContext, R.layout.view_shop_details_foot, null)
        mFooterView.tv_collect.setOnClickListener(this)
        mFooterView.tv_phone.setOnClickListener(this)
        mFooterView.tv_navigation.setOnClickListener(this)
        return mFooterView
    }

    override fun initEvent() {

        rec_shop_details.setOnSlideFinishListener {
            finish()
            overridePendingTransition(0,R.anim.translate_out)
        }
        rec_shop_details.addOnItemTouchListener(object : OnItemClickListener(){

            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val intent = Intent(mContext, GoodsDetailsActivity::class.java)
                intent.putExtra("good_id",mAdapter.data[position].id)
                startActivityForResult(intent,Constants.ACTIVITY_FINISH_REQUEST_CODE)
                (mContext as Activity).overridePendingTransition(R.anim.translate_in,R.anim.scale_out2)
            }

        })


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //关闭activity
        if (requestCode==Constants.ACTIVITY_FINISH_REQUEST_CODE){
            if (resultCode==Constants.ACTIVITY_FINISH_RESULT_CODE) {
                finish()
            }
        }
    }

    override fun onClick(view: View?) {
        when(view!!.id){
            R.id.iv_close->{
                finish()
            }
            R.id.rl_photo->{//图片列表
                val intent = Intent(mContext, ShopPhotoListActivity::class.java)
                val toJson = Gson().toJson(shopListImages)
                intent.putExtra("shopListImages",toJson)
                intent.putExtra("title",mData.shop_name)
                startActivityForResult(intent,Constants.ACTIVITY_FINISH_REQUEST_CODE)
                (mContext as Activity).overridePendingTransition(R.anim.translate_in,R.anim.scale_out2)
            }
            R.id.rl_level->{//评级
                val intent = Intent(mContext, CommentListActivity::class.java)
                intent.putExtra("shop_id",mShop_id)
                startActivityForResult(intent,Constants.ACTIVITY_FINISH_REQUEST_CODE)
                (mContext as Activity).overridePendingTransition(R.anim.translate_in,R.anim.scale_out2)
            }
            R.id.tv_check_all->{//查看全部商品
                val intent = Intent(mContext, ShopGoodsListActivity::class.java)
                intent.putExtra("shop_id",mShop_id)
                intent.putExtra("shop_name",mData.shop_name)
                startActivityForResult(intent,Constants.ACTIVITY_FINISH_REQUEST_CODE)
                (mContext as Activity).overridePendingTransition(R.anim.translate_in,R.anim.scale_out2)
            }
            R.id.tv_collect->{//收藏商家
                if ("0"==mData.is_collect){//未收藏
                    getPresenter().collectShop(mShop_id)
                }else{//改收藏
                    getPresenter().cancelCollect(mShop_id)
                }
            }
            R.id.tv_navigation->{//导航到这里

                val navigateDialog = NavigateDialog(mContext, R.style.AnimBottom)
                navigateDialog.setSelectNavigateModelListener(object : NavigateDialog.OnSelectNavigateModelListener{

                    override fun gaoDeMap() { //高德地图
                        OpenNavigationUtils.openGaode(mData.latitude,mData.longitude)
                        navigateDialog.dismiss()
                    }

                    override fun baiDuMap() { //百度地图
                        val gaoDeToBaidu = OpenNavigationUtils.gaoDeToBaidu(mData.longitude.toDouble(), mData.latitude.toDouble())
                        OpenNavigationUtils.openBaidu(gaoDeToBaidu[1].toString(),gaoDeToBaidu[0].toString())
                        navigateDialog.dismiss()
                    }
                })
                navigateDialog.show()
            }
            R.id.tv_phone->{ //致电
                val textDialog = TextDialog(mContext)
                textDialog.setTitle("拨打电话",true)
                textDialog.setContent(mTellPhone)
                textDialog.setConfirmButtonText("拨打")
                textDialog.show()
                textDialog.setOnBtnClickListener(object : TextDialog.OnBtnClickListener{

                    override fun confirm() {
                        mPermissionsManager.requestPermission()
                        textDialog.dismiss()
                    }
                    override fun cancel() {
                        textDialog.dismiss()
                    }
                })
            }
            R.id.rl_3->{//点击地图
                val intent = Intent(mContext, MapActivity::class.java)
                intent.putExtra("latitude",mData.latitude)
                intent.putExtra("longitude",mData.longitude)
                startActivity(intent)
            }
        }
    }

    override fun returnPermissionArr(): Array<out String>? {
        return needPermission
    }

    override fun requestPermissionsSuccess() {
        val intent = Intent("android.intent.action.CALL", Uri.parse("tel:" + mTellPhone))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }

    override fun requestPermissionsFailed() {
        mPermissionsManager.showOpenSettingDialogSingle(this)
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mHeaderView2.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mHeaderView2.mapView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mHeaderView2.mapView.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mHeaderView2.mapView.onSaveInstanceState(outState)
    }


    private lateinit var shopListImages : List<String>
    private lateinit var mTellPhone : String
    private lateinit var mData : ShopDetailsEntity
    override fun setData(data: ShopDetailsEntity?) {
        fl_loading.visibility=View.GONE
        mData= data!!
        if(!data?.shop_imgs.isEmpty()){
            ImageLoader.loadToUrl(mContext,mHeadImage,Constants.getBaseUrl()+data?.shop_imgs[0])
        }else{
            mHeadImage.setImageResource(R.drawable.print_load_)
        }

        mTellPhone=data!!.contract
        mHeaderView1.tv_title.text=data?.shop_name
        mHeaderView1.tv_intro.text=data?.introduce
        shopListImages = data!!.shop_imgs
        mHeaderView1.tv_count.text=shopListImages.size.toString() + resources.getString(R.string.tv_sheet)
        mHeaderView2.tv_content.text=data?.dscp
        if ("0"==data.is_collect){//已收藏
            mFooterView.tv_collect.text=getString(R.string.collect_shop)
        }else{//未收藏
            mFooterView.tv_collect.text=getString(R.string.cancel_collect_shop)
        }
        val location = Constants.getLocation()
        val myLatLng = LatLng(location[0].toDouble(), location[1].toDouble())
        val shopLatLng = LatLng(data.latitude.toDouble(), data.longitude.toDouble())
        mAMap!!.animateCamera(CameraUpdateFactory.newLatLngZoom(shopLatLng, 20.0f))
        val distanceMeters = AMapUtils.calculateLineDistance(myLatLng, shopLatLng).toDouble()
        val scale = BigDecimal(distanceMeters / 1000).setScale(2,BigDecimal.ROUND_DOWN)
        mHeaderView2.tv_distance.text= scale.toString()+"KM"
        if (data.recommend_goods.isEmpty()){
            mHeaderView2.rl_4.visibility=View.GONE
        }
        mAdapter.setNewData(data.recommend_goods)

    }

    override fun onDataFailure(msg: String?) {
    }

    /**
     * 收藏商家成功
     */
    override fun onCollectShopSuccess(msg: String?) {
        showToast(msg)
        getPresenter().loadData(mShop_id)
    }

    /**
     * 取消收藏成功
     */
    override fun onCancelCollectSuccess(msg: String?) {
        showToast(msg)
        getPresenter().loadData(mShop_id)
    }

}